package com.sgb.kjwl.view.ui.fragment.shop;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentGroupBuyChildBinding;
import com.sgb.kjwl.di.shopping.DaggerShoppingFragComponent;
import com.sgb.kjwl.di.shopping.ShoppingFragModule;
import com.sgb.jicai.entity.CentralizedMiningEntity;
import com.swgk.core.view.entity.MenuEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.jicai.event.JiCaiEventEntity;
import com.sgb.kjwl.view.event.ChooseAreaEvent;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.adapter.shopping.GroupBuyAdapter;
import com.sgb.kjwl.view.widget.PickAreaPopWindow;
import com.sgb.link.view.widget.PickCityPopWindow;
import com.sgb.kjwl.viewmodel.shopping.ShopGroupBuyChildModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 2020-12-25  商品集采列表
 * 当前作为集采单独页面下ViewPage中的Fragment
 * Author chent
 */
public class ShopGroupBuyChildFragment extends AppLazyFragment {
    @Inject
    ShopGroupBuyChildModel viewModel;
    private FragmentGroupBuyChildBinding binding;
    public static final String KEY_TYPE = "type";
    public static final String GROUP_KEY_TYPE = "groupBuyType";
    private static final String KEY_CENTRALIZED = "centralized";
    private static final String KEY_KEYWORDS = "searchWords";

    private GroupBuyAdapter groupBuyAdapter;

    private PickCityPopWindow pickTypePopWindow;
    private PickCityPopWindow pickMethodPopWindow;
    private PickSelectEntity all;

    private List<PickSelectEntity> timeDatas = new ArrayList<>();
    private List<PickSelectEntity> cityAreaDatas = new ArrayList<>();
    private List<PickSelectEntity> typeDatas = new ArrayList<>();
    private List<PickSelectEntity> methodDatas = new ArrayList<>();
    private String keyWords = "";

    private List<PickSelectEntity> provinceDatas = new ArrayList<>();
    private List<PickSelectEntity> cityDatas = new ArrayList<>();
    private PickAreaPopWindow addrPopWindow;
    private String areacode = "";       //省
    private String citysNo = "";    //地区
    //时间
    private String timeNo = "";
    //二级分类编号
    private String secondTypeNo;
    private String type;

    private String methodNo;//集采方式


    private String groupType;// “1”.即报集采、“2”.汇集采购、“”.集采大厅、“3”.企业专项、

    private int mCentralized;
    private boolean isFirstLoadData = true;


    public static ShopGroupBuyChildFragment newInstance(int index, String type, String groupBuyType) {
        ShopGroupBuyChildFragment fragment = new ShopGroupBuyChildFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        bundle.putString(GROUP_KEY_TYPE, groupBuyType);
        fragment.setArguments(bundle);
        return fragment;
    }

    // type 分类no , groupBuyType 1 即报即采 2 汇集采购 3 企业专项（企业专项请求列表不用传groupBuyType）
    // centralized 集采分类 1商品集采 2 机械集采 3 设备集采 4 劳务集采 5房产集采 6租赁集采
    public static ShopGroupBuyChildFragment newInstance(String type, String groupBuyType, int centralized, String keyWords) {
        ShopGroupBuyChildFragment fragment = new ShopGroupBuyChildFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        bundle.putString(GROUP_KEY_TYPE, groupBuyType);
        bundle.putInt(KEY_CENTRALIZED, centralized);
        bundle.putString(KEY_KEYWORDS, keyWords);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerShoppingFragComponent.builder()
                .appComponent(appComponent)
                .shoppingFragModule(new ShoppingFragModule(ShopGroupBuyChildFragment.this))
                .build()
                .inject(this);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_group_buy_child, container, false);
        type = (String) getArguments().get(KEY_TYPE);
        groupType = (String) getArguments().get(GROUP_KEY_TYPE);
        mCentralized = getArguments().getInt(KEY_CENTRALIZED);
        keyWords = getArguments().getString(KEY_KEYWORDS);
        setViewByGroupType(groupType);
        return binding.getRoot();
    }

    //根据从哪里跳转过来的显示不同的筛选项
    private void setViewByGroupType(String whereCome) {
        switch (whereCome) {
            case ""://集采大厅
                binding.tvMethod.setVisibility(View.VISIBLE);
                binding.tvType.setVisibility(View.VISIBLE);
                break;
            case "1"://即报集采
                binding.tvMethod.setVisibility(View.GONE);
                binding.tvType.setVisibility(View.VISIBLE);
                break;
            case "2"://汇集采购
                binding.tvMethod.setVisibility(View.GONE);
                binding.tvType.setVisibility(View.VISIBLE);
                break;
            case "3"://企业专项
                binding.tvMethod.setVisibility(View.GONE);
                binding.tvType.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        binding.setViewModel(viewModel);
        binding.tvAddr.setOnClickListener(this);
        binding.tvMethod.setOnClickListener(this);
        binding.tvType.setOnClickListener(this);
        if (groupBuyAdapter == null) {
            groupBuyAdapter = new GroupBuyAdapter(getActivity(), null);
        }
        all = new PickSelectEntity();
        all.setNo("");
        all.setProjectscale("全部");
        DividerItemDecoration divider = new DividerItemDecoration(this.getContext(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this.getContext(), R.drawable.shape_list_divide_jc));
        binding.recyclerView.addItemDecoration(divider);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(groupBuyAdapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        groupBuyAdapter.setItemClickCallBack(new GroupBuyAdapter.ItemClickCallBack() {
            @Override
            public void onItemClick(CentralizedMiningEntity entity) {
                viewModel.getH5Url(entity.getNo());
            }
        });
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initFilterData();
            }

            @Override
            public void onLoadMore() {
//                viewModel.getSecondAreaCodeList(type, secondTypeNo, groupType, cityNo, statusNo, timeNo, mCentralized, keyWords, true);
                viewModel.getJiCaiList(type, secondTypeNo, groupType, areacode, citysNo, "", timeNo, mCentralized, keyWords, methodNo, "", true);
            }
        });
        initPopWindow();

        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                 /*
                SCROLL_STATE_IDLE:停止滚动
                SCROLL_STATE_DRAGGING: 用户慢慢拖动
                SCROLL_STATE_SETTLING：惯性滚动
                */
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (layoutManager.findFirstVisibleItemPosition() > 0) {
                    binding.imgBackTop.setVisibility(View.VISIBLE);
                } else {
                    binding.imgBackTop.setVisibility(View.GONE);
                }
            }
        });
        binding.imgBackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.recyclerView.scrollToPosition(0);
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        if (isFirstLoadData) {
            isFirstLoadData = false;
            getData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onVisible() {
        super.onVisible();
    }

    private void getData() {
        //        viewModel.getSecondAreaCodeList();//省份下的市级筛选需求已去掉
        //省份
        viewModel.getProvinceData();
        //时间   汇集采购和企业专项有截止时间筛选
        if ("2".equals(groupType) || "3".equals(groupType)) {//“2”.汇集采购、“3”.企业专项、
            viewModel.getDateTimeList();
        }
        viewModel.getSecondTypeList(type, mCentralized);
        viewModel.getMethodList();
        //列表
        initFilterData();
    }

    @Override
    public void onMultiClick(View v) {
        switch (v.getId()) {
            case R.id.tv_type:
                binding.tvType.contentSelect(false, true);
                showTypePopWindow();
                break;
            case R.id.tv_method:
                binding.tvMethod.contentSelect(false, true);
                showMethodPopWindow();
                break;
            case R.id.tv_addr:
                binding.tvAddr.contentSelect(false, true);
                if (null != provinceDatas && provinceDatas.size() > 0) {
                    addrPopWindow.showPopwindow(binding.llTop, 0, 0);
                    addrPopWindow.setData(provinceDatas);
                }
                break;

        }
    }

    public void showList(List<CentralizedMiningEntity> list) {
        binding.recyclerView.refreshComplete();
        binding.recyclerView.loadMoreComplete();
        if (list.size() > 0) {
            groupBuyAdapter.setDatas(list);
            binding.emptyView.setVisibility(View.GONE);
        } else {
            groupBuyAdapter.setDatas(null);
            binding.emptyView.setVisibility(View.VISIBLE);
            binding.imgBackTop.setVisibility(View.GONE);
        }
        if (list.size() < 10) {
            binding.recyclerView.setLoadingMoreEnabled(false);
        } else {
            binding.recyclerView.setLoadingMoreEnabled(true);
        }
    }

    public void showUrl(String url) {
        WebViewX5HostActivity.start(getActivity(), url);
    }

    private void initPopWindow() {
        // 集采二级分类
        pickTypePopWindow = new PickCityPopWindow(this.getContext());
        pickTypePopWindow.setBgView(binding.grayLayout);
        pickTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                secondTypeNo = (String) key1;
                initFilterData();
            }
        });
        pickTypePopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (null == secondTypeNo || "".equals(secondTypeNo)) {
                    binding.tvType.contentSelect(false, false);
                } else {
                    binding.tvType.contentSelect(true, false);
                }
            }
        });
        //集采方式
        pickMethodPopWindow = new PickCityPopWindow(this.getContext());
        pickMethodPopWindow.setBgView(binding.grayLayout);
        pickMethodPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                methodNo = (String) key1;
                initFilterData();
            }
        });
        pickMethodPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (TextUtils.isEmpty(methodNo)) {
                    binding.tvMethod.contentSelect(false, false);
                } else {
                    binding.tvMethod.contentSelect(true, false);
                }
            }
        });
        //集采地区
        addrPopWindow = new PickAreaPopWindow(getActivity());
        addrPopWindow.isVisibleBottomLayout(true);
        addrPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                boolean isCity = (boolean) key3;
                if (isCity) {
                    areacode = (String) key1;
                    citysNo = "";
                } else {
                    citysNo = (String) key1;
                }
                initFilterData();
            }
        });
        addrPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (areacode.equals("") && citysNo.equals("")) {
                  binding.tvAddr.contentSelect(false,false);
                } else {
                    binding.tvAddr.contentSelect(true,false);
                }
            }
        });
        addrPopWindow.setiButtonClick(new PickAreaPopWindow.IButtonClick() {
            @Override
            public void next(String no) {
                viewModel.getCityData(no);
            }
        });
    }

    private void initFilterData() {
        viewModel.getJiCaiList(type, secondTypeNo, groupType, areacode, citysNo, "", timeNo, mCentralized, keyWords, methodNo, "", false);
    }

    public void lodMore(List<CentralizedMiningEntity> list, boolean isLastPage) {
        binding.recyclerView.refreshComplete();
        if (list.size() != 0) {
            groupBuyAdapter.addDatas(list);
        }
        if (isLastPage) {
            binding.recyclerView.setLoadingMoreEnabled(false);
        } else {
            binding.recyclerView.setLoadingMoreEnabled(true);
        }
    }


    public void setTimeDatas(List<PickSelectEntity> datas) {
        timeDatas.clear();
        datas.add(0, all);
        timeDatas.addAll(datas);
    }


    public void setcityAreaDatas(List<PickSelectEntity> datas) {
        cityAreaDatas.clear();
        datas.add(0, all);
        cityAreaDatas.addAll(datas);
    }

    public void setProvinceDatas(List<PickSelectEntity> datas) {
        provinceDatas.clear();
        provinceDatas.addAll(datas);
    }

    public void setCityDatas(List<PickSelectEntity> datas) {
        cityDatas.clear();
        cityDatas.addAll(datas);
        addrPopWindow.setCityDatas(cityDatas);
    }

    public void setMethodDatas(List<PickSelectEntity> datas) {
        methodDatas.clear();
        methodDatas.addAll(datas);
    }

    public void setSecondTypeDatas(List<MenuEntity> data) {
        List<PickSelectEntity> types = new ArrayList<>();
        if (data != null) {
            for (MenuEntity entity : data) {
                PickSelectEntity pickSelectEntity = new PickSelectEntity();
                pickSelectEntity.setNo(entity.getId());
                pickSelectEntity.setProjectscale(entity.getName());
                types.add(pickSelectEntity);
            }
        }
        typeDatas.clear();
        types.add(0, all);
        typeDatas.addAll(types);
    }


    private void showTypePopWindow() {
        pickTypePopWindow.showPopwindow(binding.tvType);
        pickTypePopWindow.setData(typeDatas);
    }

    private void showMethodPopWindow() {
        pickMethodPopWindow.showPopwindow(binding.tvMethod);
        pickMethodPopWindow.setData(methodDatas);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(ChooseAreaEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CHOOSE_AERA) {
            initFilterData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(JiCaiEventEntity event) {
        if (event.getCode() == EventConstant.EVENT_JICAI_HOME_FOUR_TYPE_SEARCH) {
            keyWords = event.getName();
            initFilterData();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
